在Pyspark中将列类型从字符串更改为日期 |
您所在的位置:网站首页 › python dataframe 更改列类型 › 在Pyspark中将列类型从字符串更改为日期 |
问题描述
我正在尝试将我的列类型从字符串更改为日期.我咨询了以下答案: 如何更改列从字符串到日期在数据范围中键入? 为什么我从date_format()获得null结果pyspark函数?当我尝试应用链接1中的答案时,我得到了无效的结果,所以我转过了链接2的答案,但我不明白这部分: output_format = ... # Some SimpleDateFormat string 推荐答案 from pyspark.sql.functions import col, unix_timestamp, to_date #sample data df = sc.parallelize([['12-21-2006'], ['05-30-2007'], ['01-01-1984'], ['12-24-2017']]).toDF(["date_in_strFormat"]) df.printSchema() df = df.withColumn('date_in_dateFormat', to_date(unix_timestamp(col('date_in_strFormat'), 'MM-dd-yyyy').cast("timestamp"))) df.show() df.printSchema()输出是: root |-- date_in_strFormat: string (nullable = true) +-----------------+------------------+ |date_in_strFormat|date_in_dateFormat| +-----------------+------------------+ | 12-21-2006| 2006-12-21| | 05-30-2007| 2007-05-30| | 01-01-1984| 1984-01-01| | 12-24-2017| 2017-12-24| +-----------------+------------------+ root |-- date_in_strFormat: string (nullable = true) |-- date_in_dateFormat: date (nullable = true) 其他推荐答案简单的方式: from pyspark.sql.types import * df_1 = df.withColumn("col_with_date_format", df["col_with_date_format"].cast(DateType())) 其他推荐答案这是一种使用默认to_date函数的更简单的方法: from pyspark.sql import functions as F df= df.withColumn('col_with_date_format',F.to_date(df.col_with_str_format))本文地址:https://www.itbaoku.cn/post/2665472.html |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |